package com.gitee.baqkft.code;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.NumberFormat;

/**
 * @Author: chenmingcai
 * @Date 2023/10/29 18:02
 **/

public class PdfImagesConvertor implements Runnable
{
    private final File pdfFile;

    private final String dir;

    private final JProgressBar bar;

    public PdfImagesConvertor(File pdfFile, String dir, JProgressBar bar)
    {
        this.pdfFile = pdfFile;
        this.dir = dir;
        this.bar = bar;
    }

    @Override
    public void run()
    {
        EventQueue.invokeLater(()->{
            bar.setVisible(true);
            bar.setString("即将开始转换...");
        });

        final NumberFormat format = NumberFormat.getInstance();
        format.setGroupingUsed(false);
        format.setMaximumIntegerDigits(4);
        format.setMinimumFractionDigits(4);
        format.setMaximumFractionDigits(0);
        format.setMinimumFractionDigits(0);

        try
        {
            PDDocument doc = PDDocument.load(pdfFile);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            EventQueue.invokeLater(()->{
                bar.setMaximum(pageCount);
            });
            for(int i = 0; i < pageCount; i++)
            {
                BufferedImage image = renderer.renderImageWithDPI(i, 600);
                ImageIO.write(image, "png", new File(dir + File.separator + format.format(i + 1) + ".png"));
                bar.setValue(i + 1);
                if( i == 0)
                {
                    EventQueue.invokeLater(()->bar.setString("正在转换中..."));
                }
            }

            EventQueue.invokeLater(()->bar.setString("转换完成"));
        }
        catch (Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }
}
